package model

import (
	"errors"
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	UserName string `gorm:"type:varchar(50);comment:账号"`
	Phone    string `gorm:"type:char(11);not null;comment:手机号"`
	Pwd      string `gorm:"type:varchar(50);not null;comment:密码"`
	Img      string `gorm:"column:img;type:varchar(255);comment:头像" json:"img"`
	Status   int64  `gorm:"type:tinyint(1);default:0;comment:用户状态:0正常,1禁用"`
	Sex      int    `gorm:"column:sex;type:int(11);default:3;comment:性别1男2女3保密" json:"sex"`
	Birthday int    `gorm:"column:birthday;type:int(11);comment:生日" json:"birthday"`
}

// 新增
func (u *User) UserSave() error {
	err := mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&u).Save(&u).Error
	})
	if err != nil {
		return err
	}
	return nil
}

// 修改
func (u *User) UserUpdate(data map[string]any) error {
	err := mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&u).Updates(data).Error
	})
	if err != nil {
		return err
	}
	return nil
}

// 用户查询
func (u *User) Userfind(data map[string]any) (*User, error) {
	var result *User
	hand := func(db *gorm.DB) error {
		err := db.Where(data).First(&result).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
		return nil
	}
	err := mysql.WithMysql(hand)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// 用户列表
func (u *User) UserList(where []int64) ([]*User, error) {
	var result []*User
	if len(where) == 0 {
		return []*User{}, nil
	}
	err := mysql.WithMysql(func(db *gorm.DB) error {
		err := db.Where("id in?", where).Find(&result).Error
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}
